﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

using Zivsoft.Utils;
using Zivsoft.Log;
/************************
 * Copyright Zivsoft.Com
 * 
 * Created by Lihua Zhou 
 * 
 ***********************/
namespace Zivsoft.Business.Spider
{
    /// <summary>
    /// 
    /// </summary>
    class HrefMatch:IHrefMatch
    {
        /// <summary>
        /// capture the url
        /// </summary>
        public const string cUrl = @"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"; 
        /// <summary>
        /// capture the jpg
        /// </summary>
        public const string REX_JPG_IN_URL = cUrl+@".jpg";

        private string _url;
        /// <summary>
        /// all validate urls
        /// </summary>
        private ArrayList _al; 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        public HrefMatch(string url)
        {
            _url = url;
            _al = new ArrayList();
        }

        /// <summary>
        /// will get the inner url
        /// </summary>
        /// <returns></returns>
        public string[] GetAllUrls()
        {
            ISearch s = new Search(_url);
            var strSource=s.GetHtmlSourceText();
            var al=s.MachItems(strSource, cUrl).ArrayListToStringArray();
            foreach (var a in al)
            {
                var keyUrl=_url.Replace("http://", "").Replace("www.", "").Replace(".net","").Replace(".com","").Replace(".cn","");
                if (a.Contains(keyUrl))
                {
                    if (a.IsPicture())
                    {
                        s.SavePicFromUrl(a, "_4");
                    }
                    else
                    {
                        _al.Add(a);
                        IHrefMatch subSearch = new HrefMatch(a);
                        var strs=subSearch.GetAllUrls();
                        foreach (var str in strs)
                        {
                            _al.Add(str);
                        }
                    }
                    Logger.LogDebug(a);
                }
            }
            return _al.ArrayListToStringArray();
        }
    }
}